package middleware

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
	"log"
)

func Auth() gin.HandlerFunc {
	return func(c *gin.Context) {
		tokenString := c.GetHeader("x-token")

		type MyCustomClaims struct {
			Foo uint32 `json:"foo"`
			jwt.RegisteredClaims
		}

		token, err := jwt.ParseWithClaims(tokenString, &MyCustomClaims{}, func(token *jwt.Token) (any, error) {
			return []byte("AllYourBase"), nil
		})
		if err != nil {
			log.Fatal(err)
		} else if claims, ok := token.Claims.(*MyCustomClaims); ok {
			fmt.Println(claims.Foo, claims.Issuer)
		} else {
			log.Fatal("unknown claims type, cannot proceed")
		}

		c.Set("user_id", token.Claims.(*MyCustomClaims).Foo)

		c.Next()
	}
}
